<template>
  <div id="selector-container" v-loading="isLoading">
    <el-drawer
      :title="
        '请选择数据集' +
        (mode === 'browse' ? '' : '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;注: 选择后将会清空 搜索/筛选 结果')
      "
      style="background-color: #e5eaf3"
      size="30%"
      v-model="drawer"
      direction="ttb"
      :before-close="switchDrawer"
    >
      <el-scrollbar>
        <div id="tag-container">
          <el-tag
            v-for="item in dataSetInfo"
            :key="item.id"
            type="success"
            :effect="currentSet.id === item.id ? 'light' : 'dark'"
            style="margin-right: 5px; height: 40px; cursor: pointer; margin-bottom: 5px"
            @click="selectSetHandle(item)"
          >
            {{ item.name }}
          </el-tag>
        </div>
      </el-scrollbar>
    </el-drawer>
    <el-button type="primary" @click="switchDrawer" round>选择数据集</el-button>
    <div id="dataSetInfo">
      <div v-if="mode === 'browse'">
        <div v-if="hasData" style="display: inline-block">
          <el-text class="mx-1" type="primary" style="font-size: large">当前数据集: &nbsp;</el-text>
          <el-text class="mx-1" type="success" style="font-size: large" tag="ins">{{ currentSet.name }}</el-text>
          <el-divider direction="vertical" style="border: 1px solid gray" />

          <div v-if="isLoadingTagFailed" style="display: inline-block">
            <el-text class="mx-1" type="danger">加载数据集标签失败</el-text>
          </div>
          <div v-else style="display: inline-block">
            <el-tag
              v-if="tagsData && tagsData.length > 0"
              v-for="tag in tagsData"
              :key="tag.id"
              effect="dark"
              type="warning"
              style="margin-right: 10px"
              round
            >
              {{ tag.content }}
            </el-tag>
            <el-text v-else class="mx-1" type="info">数据集无标签</el-text>
          </div>
        </div>
        <el-text v-else v-show="!isLoading" class="mx-1" type="warning" style="font-size: large">
          当前大类别没有任何数据集
        </el-text>
      </div>

      <div v-if="mode === 'search'">
        <el-text class="mx-1" type="primary" style="font-size: large">正在显示搜索结果: &nbsp;</el-text>
        <el-text class="mx-1" type="warning" style="font-size: large">{{ searchText }}</el-text>
      </div>

      <div v-if="mode === 'filter'">
        <el-text class="mx-1" type="primary" style="font-size: large">正在显示筛选结果: &nbsp;&nbsp;</el-text>
        <el-tag v-for="tag in filterContents" :key="tag" type="primary" effect="plain" round style="margin-right: 10px;">
          {{ tag }}
        </el-tag>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, computed } from "vue"
import { getSubCategoriesApi } from "@/api/data-manager/categoryApi"
import { getCategoryTagsApi } from "@/api/data-manager/tagApi"
import { ElMessage } from "element-plus"
import emitter from "@/utils/mitt"

const drawer = ref(false)

const props = defineProps(["categoryId"])
const categoryId = ref<string>(props.categoryId)

const isFailed = ref<boolean>(false)
const isLoading = ref<boolean>(true)

const tagsData = ref<any[]>([])
const isLoadingTagFailed = ref<boolean>(false)

const dataSetInfo = ref<any>()
const currentSet = ref<any>()

type modeType = "search" | "filter" | "browse"

const mode = ref<modeType>("browse")

const searchText = ref<string>("")
const filterContents = ref<string[]>([])

const hasData = computed(() => {
  return dataSetInfo.value && dataSetInfo.value.length > 0
})

onMounted(() => {
  setTimeout(async () => {
    let setRes
    if (!categoryId.value) {
      return
    }
    try {      
      setRes = await getSubCategoriesApi(categoryId.value)
    } catch (error) {
      ElMessage.error("获取数据集列表失败，请稍后再试")
      isFailed.value = true
      isLoading.value = false
      return
    }
    dataSetInfo.value = setRes.data

    isLoading.value = false
    selectSetHandle(setRes.data[0])
  })

  emitter.on("DM:search-image-start", (data: any) => {
    mode.value = "search"
    searchText.value = data.data
  })

  emitter.on("DM:filter-image-start", (data: any) => {
    filterContents.value = data.content
    mode.value = "filter"
  })

  emitter.on("DM:category-tag-change",() => {
    selectSetHandle(currentSet.value)
  })

  emitter.on("DM:tag-change",() => {
    selectSetHandle(currentSet.value)
  })

  emitter.on("DM:subcatrgory-change",async () => {
    let res
    res = await getSubCategoriesApi(categoryId.value)
    if (!res.data) {
      return
    }
    dataSetInfo.value = res.data
    selectSetHandle(res.data[0])
  })
})

export interface DataSetModel {
  id: string
  name: string
  p_class_id: string
  imageAmount: number
}

function selectSetHandle(data: DataSetModel) {
  mode.value = "browse"
  setTimeout(async () => {
    let tagRes
    try {
      tagRes = await getCategoryTagsApi(data.id)
      tagsData.value = tagRes.data
      isLoadingTagFailed.value = false
    } catch (error) {
      isLoadingTagFailed.value = true
    }
  })

  currentSet.value = data
  emitter.emit("DM:set-change", data)
}

function switchDrawer() {
  if (isFailed.value) {
    ElMessage.error("获取数据集列表失败，请稍后再试")
    return
  } else if (!hasData) {
    ElMessage.info("当前大类别没有任何数据集")
    return
  }
  drawer.value = !drawer.value
}
</script>

<style lang="scss" scoped>
#selector-container {
  user-select: none;
  grid-column: 1/3;
}
#dataSetInfo {
  display: inline-block;
  margin-left: 15px;
}
#tag-container {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
}
</style>
